package com.example.reschain.demo03;

import com.example.reschain.demo02.OrderContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2024年10月09日
 * @Description 参考博客：https://www.51cto.com/article/720107.html
 */
@Component
public class OrderHandleManager {

    @Autowired
    private List<AbstractOrderHandle> orderHandleList;

    @PostConstruct
    public void init(){
        // 如果List没有按照@Order注解方式排序，可以通过如下方式手动排序. AnnotationAwareOrderComparator 是一个比较器，可以根据 @Order 注解的值对列表进行排序
        orderHandleList.sort(AnnotationAwareOrderComparator.INSTANCE);
        for (int i = 0; i < orderHandleList.size(); i++) {
            if (i == orderHandleList.size() - 1){
                orderHandleList.get(i).setNext(null);
            }else {
                orderHandleList.get(i).setNext(orderHandleList.get(i + 1));
            }
        }
    }


    /**
     * 执行处理
     * @param context
     * @return
     */
    public OrderContext execute(OrderContext context){
        context = orderHandleList.get(0).execute(context);
        return context;
    }

}
